package com.slipper.codeless.resolve.update;

import com.slipper.common.bo.UserDetail;
import com.slipper.constants.Constants;
import com.slipper.exception.CommonException;
import com.slipper.system.codeless.bo.DataFieldBO;
import com.slipper.system.codeless.bo.DataModelBO;
import com.slipper.util.DateUtil;
import com.slipper.util.Tool;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class UpdateResolver {
    public Update resolve(DataModelBO dataModel, Map<String, Object> data, UserDetail user) {
        DataFieldBO dataFieldBO = dataModel.getFieldList().stream()
                .filter(field -> Constants.YES.equals(field.getPrimaryKey()))
                .findFirst()
                .orElse(null);
        boolean insert = dataFieldBO != null && Tool.isBlank(data.get(dataFieldBO.getFieldName()));
        return resolve(dataModel, data, user, insert);
    }

    public Update resolve(DataModelBO dataModel, Map<String, Object> data, UserDetail user, boolean insert) {
        if (dataModel == null) throw new CommonException("数据模型不存在！");
        if (data.isEmpty()) throw new CommonException("未提交要更新的数据！");

        Update update = new Update();
        update.setInsert(insert);
        update.setTableName(dataModel.getCode());
        dataModel.getFieldList().stream()
                .filter(field -> !DataFieldBO.FIELD_TYPE_DERIVE.equals(field.getFieldType()))
                .forEach(dataField -> {
                    if (Constants.YES.equals(dataField.getPrimaryKey())) {
                        update.setPkIdName(dataField.getFieldName());
                        update.setPkIdValue(data.get(dataField.getFieldName()));
                    } else if (data.containsKey(dataField.getFieldName())) {
                        if (!insert && ("create_id".equalsIgnoreCase(dataField.getFieldName())
                                || "create_name".equalsIgnoreCase(dataField.getFieldName())
                                || "create_time".equalsIgnoreCase(dataField.getFieldName()))) {
                            return;
                        }

                        UpdateField updateField = new UpdateField();
                        updateField.setName(dataField.getFieldName());

                        Object value = data.get(dataField.getFieldName());
                        updateField.setValue(value);
                        updateField(updateField, dataField, value, user, insert);
                        update.addUpdateField(updateField);
                    } else {
                        Object value = data.get(dataField.getFieldName());
                        UpdateField updateField = new UpdateField();
                        updateField(updateField, dataField, value, user, insert);
                        if (Tool.isNotBlank(updateField.getValue()) || Tool.isNotBlank(updateField.getValueType())) {
                            updateField.setName(dataField.getFieldName());
                            update.addUpdateField(updateField);
                        }
                    }
                });

        return update;
    }

    private static void updateField(
            UpdateField updateField,
            DataFieldBO dataField,
            Object fieldValue,
            UserDetail user,
            boolean insert) {
        // 内置字段设置值
        if ("update_id".equalsIgnoreCase(dataField.getFieldName())) {
            updateField.setValue(user == null ? null : user.getEmployeeId());
        } else if ("update_name".equalsIgnoreCase(dataField.getFieldName())) {
            updateField.setValue(user == null ? null : user.getEmployee().getName());
        } else if ("update_time".equalsIgnoreCase(dataField.getFieldName())) {
            updateField.setValue(System.currentTimeMillis());
        }

        // 新增时设置创建人信息
        if (insert && "create_id".equalsIgnoreCase(dataField.getFieldName())) {
            updateField.setValue(user == null ? null : user.getEmployeeId());
        } else if ("create_name".equalsIgnoreCase(dataField.getFieldName())) {
            updateField.setValue(user == null ? null : user.getEmployee().getName());
        }  else if (insert && "create_time".equalsIgnoreCase(dataField.getFieldName())) {
            updateField.setValue(System.currentTimeMillis());
        }

        if (Tool.isBlank(fieldValue) || !DataFieldBO.FIELD_TYPE_DATETIME.equals(dataField.getFieldType())) return;

        if (fieldValue instanceof String value) {
            if (value.matches("^\\d+$")) {
                updateField.setValue(Long.parseLong(value));
            } else {
                try {
                    updateField.setValue(DateUtil.parseDate(value).getTime());
                } catch (Exception e) {
                    throw new CommonException("【" + fieldValue + "】转换成日期出错！");
                }
            }
        } else if (fieldValue instanceof Date date) {
            updateField.setValue(date.getTime());
        }
    }
}
